package com.x.reader.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;

import com.x.framework.exception.BusinessException;
import com.x.framework.exception.ExceptionCode;
import com.x.framework.service.BaseService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;

import javax.imageio.ImageIO;

public class PdfUtil extends BaseService {
    private final static String sperator = "/";

    public static int getNumberOfPages(String filePath) throws Exception {
        PDDocument pdDocument = PDDocument.load(new File(filePath));
        int pages = pdDocument.getNumberOfPages();
        pdDocument.close();
        return pages;
    }

    public static int pdfToImage(File pdfFile, File imageFile, int pageIndex) {
        try {
//        InputStream is = null;
            int pageSize = 0;
            if (pdfFile.exists() && pdfFile.isFile()) {
                PDDocument pdDocument = null;
//            ByteArrayOutputStream os = new ByteArrayOutputStream();
                try {
                    pdDocument = PDDocument.load(pdfFile);
                    pageSize = pdDocument.getNumberOfPages();
                    if (!imageFile.exists()) {
                        PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);
                        if (pageSize > 0 && pageIndex >= 0 && pageIndex < pageSize) {
                            BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(pageIndex, 105, ImageType.RGB);
                            ImageIO.write(bufferedImage, "png", imageFile);
//                    is = new ByteArrayInputStream(os.toByteArray());
                        }
                    }
                } finally {
//                os.close();
                    if (pdDocument != null) {
                        pdDocument.close();
                    }
                }
            }
            return pageSize;
//        return is;
//            ImageOutputStream ios = ImageIO.createImageOutputStream(os);
//            ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpg").next();
//            imageWriter.setOutput(ios);
//            IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(bufferedImage), null);
//            ImageWriteParam imageWriteParam =imageWriter.getDefaultWriteParam();
//            imageWriteParam.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
//            imageWriteParam.setCompressionQuality(0.7f);//压缩率
//            imageWriter.write(imageMetaData,new IIOImage(bufferedImage, null, null), imageWriteParam);
            //                    ImageIO.write(image, imgType, sos);
        } catch (Exception e) {
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

    public static int pdfToImage(File pdfFile, String bookId) {
        try {
            int pageSize = 0;
            if (pdfFile.exists() && pdfFile.isFile()) {
                PDDocument pdDocument = null;
                try {
                    pdDocument = PDDocument.load(pdfFile);
                    pageSize = pdDocument.getNumberOfPages();
                    PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);
                    if (pageSize > 0) {
                        BufferedImage bufferedImage = null;
                        File imageFile = null;
                        float dpi = 105;
                        for (int pageIndex = 0; pageIndex < pageSize; pageIndex++) {
                            imageFile = new File("/", bookId + "_" + pageIndex + ".png");
                            if (!imageFile.exists()) {
                                bufferedImage = pdfRenderer.renderImageWithDPI(pageIndex, dpi, ImageType.RGB);
                                ImageIO.write(bufferedImage, "png", imageFile);
                            }
                        }
                    }
                } finally {
                    if (pdDocument != null) {
                        pdDocument.close();
                    }
                }
            }
            return pageSize;
        } catch (Exception e) {
            throw new BusinessException(ExceptionCode.EXCEPTION_CODE0000, e);
        }
    }

    public static void main(String[] args) {
        try {
            File pdfFile = new File("E:\\", "2019-10-18.pdf");
            if (pdfFile.exists() && pdfFile.isFile()) {
                PDDocument pdDocument = PDDocument.load(pdfFile);
                try {
                    PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);
                    int pages = pdDocument.getNumberOfPages();
                    BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(0, 100);
                    File imgFile = new File("E:\\", "2019-10-18.png");
                    ImageIO.write(bufferedImage, "png", imgFile);
                } finally {
                    pdDocument.close();
                }
            }
//            readPdf();
            //取得F盘下的pdf的内容
//            readPdf("F:/SJXLX/心理咨询师考试重点整理---20150429.pdf");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 传入一个.pdf文件
     *
     * @throws Exception
    public static void readPdf() throws Exception {
    String path = "/opt/apache-tomcat-8.5.15/webapps/reader/upload/book/file";
    //        String path = "F:/photo";
    File dir = new File(path);
    String[] fileNameArray = dir.list();
    File pdfFile;
    File txtFile;


    // pdf文件名
    // 编码方式
    String encoding = "UTF-8";

    // 文件输入流，生成文本文件
    Writer output;
    // 内存中存储的PDF Document
    PDDocument document;
    // PDFTextStripper来提取文本
    PDFTextStripper stripper;
    // 调用PDFTextStripper的writeText提取并输出文本
    //        URL url;
    try {
    //            try {
    for (String pdfName : fileNameArray) {
    if (pdfName.indexOf(".pdf") > -1) {
    // 首先当作一个URL来装载文件，如果得到异常再从本地文件系统//去装载文件
    //                        url = new URL(path + sperator + pdfName);
    //注意参数已不是以前版本中的URL.而是File。
    // 以原来PDF的名称来命名新产生的txt文件
    if (pdfName.length() > 4) {
    txtFile = new File(path, pdfName.substring(0, pdfName.length() - 4) + ".txt");
    if (!txtFile.exists()) {
    stripper = new PDFTextStripper();
    // 设置是否排序
    stripper.setSortByPosition(false);// 是否排序
    // 设置起始页
    stripper.setStartPage(1);// 开始提取页数
    // 设置结束页
    stripper.setEndPage(Integer.MAX_VALUE);// 结束提取页数

    output = new OutputStreamWriter(new FileOutputStream(txtFile), encoding);
    pdfFile = new File(dir, pdfName);
    document = PDDocument.load(pdfFile);
    stripper.writeText(document, output);
    if (output != null) {
    // 关闭输出流
    output.close();
    }
    if (document != null) {
    // 关闭PDF Document
    document.close();
    }
    }
    }
    }
    }
    //            } catch (MalformedURLException e) {
    // 如果作为URL装载得到异常则从文件系统装载
    //注意参数已不是以前版本中的URL.而是File。
    //                document = PDDocument.load(pdfFile);
    //                if (pdfFile.length() > 4) {
    //                    textFile = pdfFile.substring(0, pdfFile.length() - 4) + ".txt";
    //                }
    //            }
    // 文件输入流，写入文件倒textFile

    System.out.println(" 输出成功！");
    } catch (Exception e){
    e.printStackTrace();
    //            if (output != null) {
    //                // 关闭输出流
    //                output.close();
    //            }
    //            if (document != null) {
    //                // 关闭PDF Document
    //                document.close();
    //            }
    }
    }
     */
}

